package com.smg.crm.interceptor;

import com.smg.crm.exception.InterceptorException;
import com.smg.crm.exception.LoginException;
import com.smg.crm.settings.domain.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    //控制器方法访问之前执行
    //返回true,代表放行,允许访问控制器
    //返回false,代表拦截,无法访问后续的控制器
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        User user = (User) httpServletRequest.getSession().getAttribute("user");

        if(user == null){
            //如果没有登录,直接跳转到登录页面
            //方式1:抛出异常,交给异常处理器进行处理
            //返回json
//            throw new LoginException("用户未登录");
            //方式2:抛出拦截异常,交给异常处理器进行处理
            //跳转到登录页面
            throw new InterceptorException();
            //方式2:返回false,让拦截器进行拦截,不让访问后续的控制器
//            return false;
        }
        //当用户登录后,允许他访问后续的控制器
        return true;
    }

    //控制器方法访问之后执行
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    //页面加载完成后执行
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
